﻿using KM.Data;
using KM.Framework.Business;
using KM.Framework.Utility;
using Microsoft.Practices.Prism.Commands;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;



namespace Sale.Client
{
   public class MainWindowViewModel: ViewModelBase
    {
    
        private List<InvoiceFileData> _DataList;
        public List<InvoiceFileData> DataList
        {
            get { return _DataList??new List<InvoiceFileData>(); }
            set
            {
                _DataList = value;
                this.RaisePropertyChanged("DataList");
            }
        }
        private InvoiceFileData _SelectObject;
        public InvoiceFileData SelectObject
        {
            get { return _SelectObject; }
            set
            {
                _SelectObject = value;
                this.RaisePropertyChanged("SelectObject");
            }
        }
        private string _InvoiceDrectory;
        public string InvoiceDrectory
        {
            get { return _InvoiceDrectory; }
            set
            {
                _InvoiceDrectory = value;
                this.RaisePropertyChanged("InvoiceDrectory");
            }
        }
        private int _AllCounnt;
        public int AllCounnt
        {
            get { return _AllCounnt; }
            set
            {
                _AllCounnt = value;
                this.RaisePropertyChanged("AllCounnt");
            }
        }
        public DelegateCommand SelectDrectoryCommand { get; set; }
        public DelegateCommand DownloadCommand { get; set; }
        public MainWindowViewModel()
        {
            InitCommand();
            LoadData();
        }
        private void InitCommand()
        {
            SelectDrectoryCommand = CreateCommand(() => {
                try
                {
                    using (System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog())
                    {
                        dialog.Description = "请选择一个文件夹";
                        dialog.RootFolder = Environment.SpecialFolder.MyComputer;
                        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            string selectedPath = dialog.SelectedPath;
                            if (!selectedPath.IsNullOrEmptyOrWhiteSpace())
                                InvoiceDrectory = selectedPath;
                        }
                    }
                }
                catch (Exception ex)
                {
                    BoxHelper.Error(ex.Message);
                    return;
                }
            
            });
            DownloadCommand = CreateCommand(() => {
                if (InvoiceDrectory.IsNullOrEmptyOrWhiteSpace())
                {
                    BoxHelper.Error("请选择下载文件夹!!!");
                    return;
                }
                if (DataList==null||DataList.Count<1)
                {
                    BoxHelper.Error("无可以下载数据!!!");
                    return;
                }
                if (!Directory.Exists(InvoiceDrectory))
                    Directory.CreateDirectory(InvoiceDrectory);
                //using (WebClient client = new WebClient())
                //{

                //}
                foreach (InvoiceFileData data in DataList)
                {
                    try
                    {
                        string fpname = $@"{data.invoiceNumber}_{data.invoiceDate}_{data.invoiceTittle}_{data.amount}.pdf";
                        string path = $@"{InvoiceDrectory}\{fpname}";
                        if (File.Exists(path))
                        {
                            data.msg = "该发票文件已存在";
                            continue;
                        }
                        if (data.networkAddress.IsNullOrEmptyOrWhiteSpace())
                        {
                            data.msg = "网络路径有误";
                            continue;
                        }
                        using (WebClient client = new WebClient())
                        {
                            client.DownloadFile(data.networkAddress, path);
                            data.msg = "下载完成";
                        }
                    }
                    catch (Exception ex)
                    {
                        data.msg = "下载异常";
                        continue;
                    }
                }

                List<InvoiceFileData> datas = DataList;
                DataList = new List<InvoiceFileData>();
                DataList = datas;
                AllCounnt = DataList.Count;
            });

        }
        public void LoadData()
        {
            try
            {
                DataList = new List<InvoiceFileData>();
                DataList = ReadData();
                AllCounnt = DataList.Count;
            }
            catch (Exception ex)
            {
                BoxHelper.Info(ex.Message);
                return;
            }
            

        }
        public List<InvoiceFileData> ReadData() 
        {
            string txtpath = CommonData.TxtHeader + "/" + CommonData.InValue;
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string inpath1 = $@"{path}InvoiceTxt";
            string inpath = $@"{inpath1}/{CommonData.InValue}";
            if (!Directory.Exists(inpath1))
            {
                Directory.CreateDirectory(inpath1);
            }
            if (File.Exists(inpath))
            {
                File.Delete(inpath);
                File.Create(inpath).Close();
            }
            else
            {
                File.Create(inpath).Close();
            }
            using (WebClient client = new WebClient())
            {
                client.DownloadFile(txtpath, inpath);
            }
            List<ExcelCol> colList = new List<ExcelCol>();
            NPOIHelper helper = new NPOIHelper();
            helper.Open(inpath);
            ISheet sheet = helper.Workbook.GetSheetAt(0);
            IRow rowHeader = sheet.GetRow(0);
            for (int i = 0; i < rowHeader.Cells.Count; i++)
            {
                ICell c1 = rowHeader.GetCell(i);
                string name = helper.GetCellValue(c1);
                if (name == "单号")
                    colList.Add(new ExcelCol() { cIndex = i, cName = name });
                else if (name == "发票号码")
                    colList.Add(new ExcelCol() { cIndex = i, cName = name });
                else if (name == "发票日期")
                    colList.Add(new ExcelCol() { cIndex = i, cName = name });
                else if (name == "发票抬头")
                    colList.Add(new ExcelCol() { cIndex = i, cName = name });
                else if (name == "发票价税合计")
                    colList.Add(new ExcelCol() { cIndex = i, cName = name });
                else if (name == "电子发票地址")
                    colList.Add(new ExcelCol() { cIndex = i, cName = name });

            }
            if (colList.Count < 6)
            {
                BoxHelper.Error($@"传输数据有误【{inpath}】");
                return new List<InvoiceFileData>();
            }
            List<InvoiceFileData> datas = new List<InvoiceFileData>();
            for (int i = 1; i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row == null || row.Cells.Count < 1 || row.Cells.Count < 6)
                    break;
                InvoiceFileData ed = new InvoiceFileData();
                foreach (ExcelCol col in colList)
                {
                    ICell cell = row.GetCell(col.cIndex);
                    if (cell == null)
                        continue;
                    string value = helper.GetCellValue(cell);
                    if (col.cName == "单号")
                        ed.billNo = value.ToStringV1();
                    else if (col.cName == "发票号码")
                        ed.invoiceNumber = value.ToStringV1();
                    else if (col.cName == "发票日期")
                        ed.invoiceDate = value.ToStringV1();
                    else if (col.cName == "发票抬头")
                        ed.invoiceTittle = value.ToStringV1();
                    else if (col.cName == "发票价税合计")
                        ed.amount = value.ToStringV1();
                    else if (col.cName == "电子发票地址")
                        ed.networkAddress = value.ToStringV1();
                }
                datas.Add(ed);
            }
            return datas;

        }


        //public void Query(int size, int pageIndex)
        //{
        //    LoadData(size, pageIndex);
        //}

    }
    public class ExcelCol
    {
        public int cIndex { get; set; }
        public string cName { get; set; }
    }
}
